package com.github.wxiaoqi.security.crm.core.biz;

import java.math.BigDecimal;
import java.text.Bidi;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.common.crm.request.BalanceUnFreAndOutAccountRequest;
import com.github.wxiaoqi.security.common.crm.request.RefundFreezeRequest;
import com.github.wxiaoqi.security.common.crm.request.RefundUnFreezeRequest;
import com.github.wxiaoqi.security.common.crm.request.UnFreAndOutAccountRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.crm.core.entity.FreezeJournal;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccount;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccountJournal;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccount;
import com.github.wxiaoqi.security.crm.core.entity.PersonalAccountJournal;
import com.github.wxiaoqi.security.crm.core.entity.PersonalBilling;
import com.github.wxiaoqi.security.crm.core.entity.UnfreezeJournal;
import com.github.wxiaoqi.security.crm.core.mapper.FreezeJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalAccountMapper;
import com.github.wxiaoqi.security.crm.core.mapper.PersonalBillingMapper;
import com.github.wxiaoqi.security.crm.core.mapper.UnfreezeJournalMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 退款相关的操作接口--解冻并出账接口（包括第三方支付和余额账户支付）
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class RefundUnFreAndOutAccountBiz {
	@Value("${bountyHunter.balanceSaltValue}")
	private String balanceSaltValue;
	@Autowired
	private PersonalBillingMapper personalBillingMapper;
	@Autowired
	private MerchantAccountJournalMapper merchantAccountJournalMapper;
	@Autowired
	private MerchantAccountMapper merchantAccountMapper;
	@Autowired
	private UnfreezeJournalMapper unfreezeJournalMapper;
	@Autowired
	private PersonalAccountMapper personalAccountMapper;
	@Autowired
	private PersonalAccountJournalMapper personalAccountJournalMapper;
	/**
	 * 第三方支付-退款成功则需要解冻资金并出账接口
	 * 1.商户账户冻结金额扣除
	 * 2.新增商户流水记录、解冻流水记录
	 * 3.个人账单原退款申请记录置为成功
	 * 
	 */
	public Map<String, Object> unFreAndOutAccount(UnFreAndOutAccountRequest unFreAndOutAccountRequest) {
		log.info("退款成功后(第三方支付)解冻资金并出账接口-请求参数：{}" + EntityUtils.beanToMap(unFreAndOutAccountRequest));
		Map<String, Object> response = new HashMap<String, Object>();
		/**
		 * 根据冻结流水号查询是否被解冻
		 * */
		try {
			UnfreezeJournal queryUnfreezeJournal = new UnfreezeJournal();
			queryUnfreezeJournal.setFreezeId(unFreAndOutAccountRequest.getFreezeId());
			queryUnfreezeJournal.setOrderNo(unFreAndOutAccountRequest.getRefundOrderNo());
			UnfreezeJournal unfreezeJournal=unfreezeJournalMapper.selectOne(queryUnfreezeJournal);
			if(null!=unfreezeJournal){
				log.info("退款成功后(第三方支付)解冻资金并出账接口--冻结资金已解冻");
				response.put("code", ResponseCode.UNFREEZE_IS_EXIST.getCode());
				response.put("msg", ResponseCode.UNFREEZE_IS_EXIST.getMessage());
				return response;
			}
			MerchantAccount queryMerchantAccount=new MerchantAccount();
			queryMerchantAccount.setPlatformId(unFreAndOutAccountRequest.getPlatformId());
			queryMerchantAccount.setMerchantId(unFreAndOutAccountRequest.getMerchantId());
			queryMerchantAccount.setCustomerType(unFreAndOutAccountRequest.getCustomerType());
			queryMerchantAccount.setAccountType(unFreAndOutAccountRequest.getAccountType());
			MerchantAccount merchantAccount= merchantAccountMapper.selectOne(queryMerchantAccount);
			if(null!=merchantAccount){
				merchantAccount.setFreezeBalance(queryMerchantAccount.getFreezeBalance().subtract(new BigDecimal(unFreAndOutAccountRequest.getRefoundAmt())));
				merchantAccount.setCheckSum(MD5.sign(merchantAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8"));
				merchantAccountMapper.updateByPrimaryKeySelective(merchantAccount);
			}else{
				log.info("退款成功后(第三方支付)解冻资金并出账接口--商户账户不存在");
				response.put("code", ResponseCode.MER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/***
			 * 新增商户账户流水记录、解冻流水记录
			 * */
			MerchantAccountJournal merAccountJournal=new MerchantAccountJournal();
			merAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			merAccountJournal.setPlatformId(unFreAndOutAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(unFreAndOutAccountRequest.getMerchantId());
			merAccountJournal.setAccountId(merchantAccount.getAccountId());
			merAccountJournal.setOrderNo(unFreAndOutAccountRequest.getRefundOrderNo());
			merAccountJournal.setInOutFlag("2");//出账 
			merAccountJournal.setTradeAmt(new BigDecimal(unFreAndOutAccountRequest.getRefoundAmt()));
			merAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			merAccountJournal.setCreateTime(new Date());
			merchantAccountJournalMapper.insertSelective(merAccountJournal);
			queryUnfreezeJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			queryUnfreezeJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			queryUnfreezeJournal.setUnfreezeBalance(new BigDecimal(unFreAndOutAccountRequest.getRefoundAmt()));
			queryUnfreezeJournal.setCreateTime(new Date());
			unfreezeJournalMapper.insertSelective(queryUnfreezeJournal);
			PersonalBilling billing = new PersonalBilling();
			billing.setPlatformId(unFreAndOutAccountRequest.getPlatformId());
			billing.setOrderNo(unFreAndOutAccountRequest.getRefundOrderNo());
			billing.setPersonalId(unFreAndOutAccountRequest.getMerchantId());
			billing.setTradeType("02");
			PersonalBilling perBill=personalBillingMapper.selectOne(billing);
			if(null!=perBill){
				perBill.setStatus("03");
				personalBillingMapper.updateByPrimaryKeySelective(perBill);
				response.put("code", ResponseCode.OK.getCode());
				response.put("msg", ResponseCode.OK.getMessage());
			}else{
				log.info("退款成功后(第三方支付)解冻资金并出账接口--退款账单不存在");
				response.put("code", ResponseCode.PER_REFONDBILL_NOT_EXIST.getCode());
				response.put("msg", ResponseCode.PER_REFONDBILL_NOT_EXIST.getMessage());
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("退款成功后(第三方支付)解冻资金并出账接口-报错--"+e.getMessage());
			response.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			response.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			return response;
		}
		return response;
	}
	/**
	 * 余额账户支付-退款成功则需要解冻资金并出账接口
	 * 1.商户账户冻结金额扣除、个人账户余额增加
	 * 2.新增商户流水记录、解冻流水记录,新增个人账户流水记录
	 * 3.个人账单原退款申请记录置为成功
	 */
	public Map<String, Object> balanceUnFreAndOutAccount(BalanceUnFreAndOutAccountRequest balanceUnFreAndOutAccountRequest) {
		log.info("退款成功后(余额账户支付)解冻资金并出账接口-请求参数：{}" + EntityUtils.beanToMap(balanceUnFreAndOutAccountRequest));
		Map<String, Object> response = new HashMap<String, Object>();
		UnfreezeJournal queryUnfreezeJournal = new UnfreezeJournal();
		queryUnfreezeJournal.setFreezeId(balanceUnFreAndOutAccountRequest.getFreezeId());
		queryUnfreezeJournal.setOrderNo(balanceUnFreAndOutAccountRequest.getRefundOrderNo());
		UnfreezeJournal unfreezeJournal=unfreezeJournalMapper.selectOne(queryUnfreezeJournal);
		if(null!=unfreezeJournal){
			log.info("退款成功后(余额账户支付)解冻资金并出账接口--冻结资金已解冻");
			response.put("code", ResponseCode.UNFREEZE_IS_EXIST.getCode());
			response.put("msg", ResponseCode.UNFREEZE_IS_EXIST.getMessage());
			return response;
		}
		try {
			/***
			 * 商户账户冻结金额扣除
			 * */
			MerchantAccount queryMerchantAccount=new MerchantAccount();
			queryMerchantAccount.setPlatformId(balanceUnFreAndOutAccountRequest.getPlatformId());
			queryMerchantAccount.setMerchantId(balanceUnFreAndOutAccountRequest.getMerchantId());
			queryMerchantAccount.setCustomerType(balanceUnFreAndOutAccountRequest.getCustomerType());
			queryMerchantAccount.setAccountType(balanceUnFreAndOutAccountRequest.getAccountType());
			MerchantAccount merchantAccount= merchantAccountMapper.selectOne(queryMerchantAccount);
			if(null!=merchantAccount){
				merchantAccount.setFreezeBalance(queryMerchantAccount.getFreezeBalance().subtract(new BigDecimal(balanceUnFreAndOutAccountRequest.getRefoundAmt())));
				merchantAccountMapper.updateByPrimaryKeySelective(merchantAccount);
			}else{
				log.info("退款成功后(余额账户支付)解冻资金并出账接口--商户账户不存在");
				response.put("code", ResponseCode.MER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.MER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/**
			 *个人账户余额增加
			 * */
			PersonalAccount queryPersonalAccount = new PersonalAccount();
			queryPersonalAccount.setPlatformId(balanceUnFreAndOutAccountRequest.getPlatformId());
			queryPersonalAccount.setPersonalId(balanceUnFreAndOutAccountRequest.getPersonalId());
			queryPersonalAccount.setAccountType(balanceUnFreAndOutAccountRequest.getAccountType());
			PersonalAccount personalAccount = personalAccountMapper.selectOne(queryPersonalAccount);
			if(null!=personalAccount){
				if(!MD5.sign(personalAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8").equals(personalAccount.getCheckSum())){
					response.put("code", ResponseCode.PER_ACC_BALANCE_NOT_MATE.getCode());
					response.put("msg", ResponseCode.PER_ACC_BALANCE_NOT_MATE.getMessage());
					log.info("退款成功后(余额账户支付)解冻资金并出账接口 返回参数。。。。。。{}", response);
					return response;
				}
				personalAccount.setAccountBalance(personalAccount.getAccountBalance().add(new BigDecimal(balanceUnFreAndOutAccountRequest.getRefoundAmt())));
				personalAccount.setCheckSum(MD5.sign(personalAccount.getAccountBalance().toString(), balanceSaltValue, "utf-8"));
				personalAccountMapper.updateByPrimaryKeySelective(personalAccount);
			}else{
				log.info("退款成功后(余额账户支付)解冻资金并出账接口--个人账户不存在");
				response.put("code", ResponseCode.PER_ACC_NOTEXIST.getCode());
				response.put("msg", ResponseCode.PER_ACC_NOTEXIST.getMessage());
				return response;
			}
			/**
			 * 新增商户流水记录、解冻流水记录、个人账户流水记录
			 * */
			MerchantAccountJournal merAccountJournal=new MerchantAccountJournal();
			merAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			merAccountJournal.setPlatformId(balanceUnFreAndOutAccountRequest.getPlatformId());
			merAccountJournal.setMerchantId(balanceUnFreAndOutAccountRequest.getMerchantId());
			merAccountJournal.setAccountId(merchantAccount.getAccountId());
			merAccountJournal.setOrderNo(balanceUnFreAndOutAccountRequest.getRefundOrderNo());
			merAccountJournal.setInOutFlag("2");//出账 
			merAccountJournal.setTradeAmt(new BigDecimal(balanceUnFreAndOutAccountRequest.getRefoundAmt()));
			merAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			merAccountJournal.setCreateTime(new Date());
			merchantAccountJournalMapper.insertSelective(merAccountJournal);
			queryUnfreezeJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			queryUnfreezeJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			queryUnfreezeJournal.setUnfreezeBalance(new BigDecimal(balanceUnFreAndOutAccountRequest.getRefoundAmt()));
			queryUnfreezeJournal.setCreateTime(new Date());
			unfreezeJournalMapper.insertSelective(queryUnfreezeJournal);
			PersonalAccountJournal personalAccountJournal=new PersonalAccountJournal();
			personalAccountJournal.setJournalId(String.valueOf(SnowFlake.getId()));
			personalAccountJournal.setPlatformId(balanceUnFreAndOutAccountRequest.getPlatformId());
			personalAccountJournal.setPersonalId(balanceUnFreAndOutAccountRequest.getPersonalId());
			personalAccountJournal.setAccountId(personalAccount.getAccountId());
			personalAccountJournal.setAccountType(personalAccount.getAccountType());
			personalAccountJournal.setOrderNo(balanceUnFreAndOutAccountRequest.getRefundOrderNo());
			personalAccountJournal.setInOutFlag("1");//来往标志  1：入账   2：出账
			personalAccountJournal.setTradeAmt(new BigDecimal(balanceUnFreAndOutAccountRequest.getRefoundAmt()));
			personalAccountJournal.setTradeType("02");//交易类型（支付:01，退款:02，提现:03，充值:04）
			personalAccountJournal.setCreateTime(new Date());
			personalAccountJournalMapper.insertSelective(personalAccountJournal);
			response.put("code", ResponseCode.OK.getCode());
			response.put("msg", ResponseCode.OK.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.info("退款成功后(余额账户支付)解冻资金并出账接口-报错--"+e.getMessage());
			response.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			response.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			return response;
		}
		return response;
	}
}
